/*
 * Copyright (C) 2009 M. Hautle.
 * 
 * This file is part of TrackedBean.
 * 
 * TrackedBean is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General
 * Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any
 * later version.
 * 
 * TrackedBean is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
 * details.
 * 
 * You should have received a copy of the GNU Lesser General Public License along with TrackedBean. If not, see
 * <http://www.gnu.org/licenses/>.
 */
package ch.trackedbean.binding.guicomponents;

import java.util.*;
import javax.swing.*;
import javax.swing.event.*;
import ch.trackedbean.binding.guicomponents.action.*;
import ch.trackedbean.binding.mapping.*;

/**
 * Handler for {@link JTable} selection dependent actions.<br>
 * The {@link Action#setEnabled(boolean)} method of a action will be called with the result of
 * {@link ISelectionAction#selectionChanged(List)} (called using the current selection).
 * 
 * @param <T> The table content type
 * 
 * @author M. Hautle
 */
public class TableSelectionActionHandler<T> implements ListSelectionListener {
	/** The list of selection dependent actions or null. */
	protected List<ISelectionAction<T>> selectionActions = new ArrayList<ISelectionAction<T>>(5);

	/** The mapping on which this handler depends. */
	protected TableMapping<T> mapping;

	/**
	 * Default constructor.
	 * 
	 * @param mapping The mapping where to append this handler
	 */
	public TableSelectionActionHandler(TableMapping<T> mapping) {
		this.mapping = mapping;
		mapping.getTable().getSelectionModel().addListSelectionListener(this);
	}

	/**
	 * Adds the given action and calls {@link ISelectionAction#selectionChanged(List)} using the current selection.
	 * 
	 * @param action Adds the given action
	 */
	public void addAction(ISelectionAction<T> action) {
		if (selectionActions.contains(action))
			return;
		selectionActions.add(action);
		action.setEnabled(action.selectionChanged(mapping.getSelectedRows()));
	}

	/**
	 * Removes the given action.
	 * 
	 * @param action Removes the given action
	 */
	public void removeAction(ISelectionAction action) {
		selectionActions.remove(action);
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void valueChanged(ListSelectionEvent e) {
		if (e.getValueIsAdjusting())
			return;
		final List<T> sel = mapping.getSelectedRows();
		for (ISelectionAction<T> a : selectionActions)
			a.setEnabled(a.selectionChanged(sel));
	}

	/**
	 * "Destroyes" the handler by freeing it's ressources and detaching it's internal listeners
	 */
	public void dispose() {
		selectionActions.clear();
		mapping.getTable().getSelectionModel().removeListSelectionListener(this);
	}
}